﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using zkdao.Domain;
using sharp_net;
using sharp_net.Repositories;
using AutoMapper;
using sharp_net.Specifications;

namespace zkdao.Application {

    public class RebateReplyApplication : BaseApplication, IRebateReplyService {
        public RebateReplyData Get(Guid ID) {
            using (var context = IocLocator.Instance.GetImple<IRepositoryContext>()) {
                var replyChildRepository = context.GetRepository<RebateReply>();
                var replyChild = replyChildRepository.GetById(ID);
                if (replyChild == null)
                    return null;
                var replyChildData = Mapper.Map<RebateReply, RebateReplyData>(replyChild);
                return replyChildData;
            }
        }

        public IEnumerable<RebateReplyData> GetListPager(string TargetID, ref int count, int pageSize = 10, int pageIndex = 1) {
            var specification = Specification<RebateReply>.Eval(r => r.RebateID == Guid.Parse(TargetID));
            using (var context = IocLocator.Instance.GetImple<IRepositoryContext>()) {
                var replyRepository = context.GetRepository<RebateReply>();
                var replys = replyRepository.FindAll(specification, pageIndex, pageSize);
                if (replys == null)
                    return null;
                count = replyRepository.FindAll(specification).Count();
                var replyDatas = new List<RebateReplyData>();
                foreach (var replyChild in replys) {
                    replyDatas.Add(Mapper.Map<RebateReply, RebateReplyData>(replyChild));
                }
                return replyDatas;
            }
        }

        public RebateReplyData Creat(RebateReplyData dataObject) {
            if (dataObject == null)
                throw new ArgumentNullException("replyChildDataObject");
            using (var context = IocLocator.Instance.GetImple<IRepositoryContext>()) {
                var replyRepository = context.GetRepository<RebateReply>();
                var reply = Mapper.Map<RebateReplyData, RebateReply>(dataObject);
                reply.Creat();
                replyRepository.Add(reply);
                context.Commit();
                return Mapper.Map<RebateReply, RebateReplyData>(reply);
            }
        }

        public void Update(RebateReplyData dataObject) {
            if (dataObject.ID == 0)
                throw new ArgumentNullException("ID");
            var replyChild = Mapper.Map<RebateReplyData, RebateReply>(dataObject);
            using (var context = IocLocator.Instance.GetImple<IRepositoryContext>()) {
                var replyRepository = context.GetRepository<RebateReply>();
                var upInfo = replyRepository.Get(Specification<RebateReply>.Eval(c => c.Id == dataObject.ID));
                upInfo.Update(dataObject);
                replyRepository.Update(upInfo);
            }
        }
    }
}